<?php
/**
 * @version $Id: FoldAway.php 26 2009-06-29 20:17:28Z joomla@nik-it.de $
 * @package		FoldAway
 * @author		Nikolai Plath (elkuku) {@link http://www.nik-it.de NiK-IT.de}
 * @author		Created on 09-Feb-2009
 *
 * Install:
 * Add
 * require_once( "$IP/extensions/PermCalc/PermCalc.php" );
 * to your LocaleSettings.php
 *
 * Usage:
 * <permcalc>Introtext(optional)</permcalc>
 *
 * Required:
 * Have Fun =;)
 */

//--No direct access
defined('MEDIAWIKI') or die('=;)');

defined('DS') or define('DS', DIRECTORY_SEPARATOR);

//Avoid unstubbing $wgParser on setHook() too early on modern (1.12+) MW versions, as per r35980
if ( defined( 'MW_SUPPORTS_PARSERFIRSTCALLINIT' ) )
{
	$wgHooks['ParserFirstCallInit'][] = 'wfFoldAway';
}
else
{ // Otherwise do things the old fashioned way
	$wgExtensionFunctions[] = 'wfFoldAway';
}

$wgExtensionCredits['parserhook'][] = array(
	'version'     => '1.0',
	'name'        => 'FoldAway',
	'author'      => array('Nikolai Plath'),
	'email'       => 'nik@',
	'url'         => 'http://www.mediawiki.org/wiki/Extension:FoldAway...soon',
	'description' => 'adds <tt>&lt;fold&gt;</tt> tags',
);

function wfFoldAway()
{
	global $wgParser, $wgHooks;
	$wgParser->setHook('fold', 'renderFoldAway');
	$wgHooks['OutputPageParserOutput'][] = 'fnFoldAwayOutputHook';

	return true;
}//function

function renderFoldAway($input, $argv, &$parser)
{
	static $foldCount;
	$foldCount ++;

	//--Set the Title
	$title =( array_key_exists('title', $argv) ) ? $argv['title'] : '&nbsp;';

	//--Parse input text
	$output = $parser->recursiveTagParse($input);

	$titleDiv = '<div class="foldAwayTitle" id="foldAwayTitle_'.$foldCount.'" onclick="toggleFold('.$foldCount.');">'.$title.'</div>';
	$foldAwayDiv = '<div class="foldAway" id="foldAway_'.$foldCount.'">'.$output.'</div>';
	$javascript = '<script type="text/javascript">toggleFold('.$foldCount.');</script>';

	return $titleDiv
			. $foldAwayDiv
			. $javascript;
}//function

/**
 * Entry point for the hook for printing JS and CSS:
 */
function fnFoldAwayOutputHook( &$m_pageObj, $m_parserOutput ) {
	if( defined('FOLD_AWAY_ADDED'))
	{
		//--Only add once
		return true;
	}
	define ('FOLD_AWAY_ADDED', 1);
	global $wgScriptPath;

	//--CSS
	$m_pageObj->addLink(
		array(
	      'rel'   => 'stylesheet',
	      'type'  => 'text/css',
	      'href'  => $wgScriptPath.'/extensions/FoldAway/FoldAway.css'
		)
	);

	//--JS
	$m_pageObj->addScriptFile($wgScriptPath.DS.'extensions'.DS.'FoldAway'.DS.'FoldAway.js');

	# Be nice:
	return true;
}//function
